<template>
  <div class="main">
    <div class="title-div">
      <div style="height: 67%">信用城市可视化大屏</div>
      <div id="timeS" style="font-size: 0.8vw;">{{ nowTime }}</div>
    </div>
    <div class="report-div">
      <div class="report-son-1" style="width: 25%">
        <div class="report-son-2" style="height: 33%">
          <div class="report-son-title">月服务开通及使用人数</div>
          <div class="report-son-body">
            <div class="left1-buts" style="height: 25%" id="left1But">
              <div>
                <el-button style="width: 65px;" class="el-button el-button--default buts"
                  :class="{ active: activeService === '信用租赁' }" @click="getLeft1('信用租赁')">
                  信用租赁
                </el-button>
                <el-button style="width: 65px;" class="el-button el-button--default buts"
                  :class="{ active: activeService === '酒店预定' }" @click="getLeft1('酒店预定')">
                  酒店预定
                </el-button>
                <el-button style="width: 65px;" class="el-button el-button--default buts"
                  :class="{ active: activeService === '便捷泊车' }" @click="getLeft1('便捷泊车')">
                  便捷泊车
                </el-button>
                <el-button style="width: 65px;" class="el-button el-button--default buts"
                  :class="{ active: activeService === '舒心就医' }" @click="getLeft1('舒心就医')">
                  舒心就医
                </el-button>
              </div>
            </div>
            <div style="height: 75%" id="left1"></div>
          </div>
        </div>
        <div class="report-son-2" style="height: 33%">
          <div class="report-son-title">各项服务授信额度</div>
          <div class="report-son-body" id="left2"></div>
        </div>
        <div class="report-son-2" style="height: 33%">
          <div class="report-son-title">各地区信用分分布</div>
          <div class="report-son-body" id="left3"></div>
        </div>
      </div>
      <div class="report-son-1" style="width: 50%">
        <div class="mid1-1-body" style="height: 33%">
          <div class="report-son-1-1">
            <div class="report-son-1-1-body" id="mid1-1">{{ zsyNum }}</div>
            <div class="report-son-1-1-title">周使用量</div>
          </div>
          <div class="report-son-1-1">
            <div class="report-son-1-1-body" id="mid1-2">{{ syNum }}</div>
            <div class="report-son-1-1-title">总使用量</div>
          </div>
          <div class="report-son-1-1">
            <div class="report-son-1-1-body" id="mid1-3">{{ ktNum }}</div>
            <div class="report-son-1-1-title">总开通量</div>
          </div>
        </div>
        <div class="report-son-2" style="height: 66%" id="mid2"></div>
      </div>
      <div class="report-son-1" style="width: 25%">
        <div class="report-son-2" style="height: 56%">
          <div class="report-son-title">用户画像</div>
          <div class="report-son-body">
            <div class="report-son-body-1">
              <div class="report-son-body-2" id="right1-1"></div>
              <div class="report-son-body-2" id="right1-2"></div>
              <div class="report-son-body-2" id="right1-3"></div>
              <div class="report-son-body-2" id="right1-4"></div>
            </div>
          </div>
        </div>
        <div class="report-son-2" style="height: 43%">
          <div class="report-son-title">人群收入情况</div>
          <div class="report-son-body" id="right2"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';
import * as echarts from 'echarts';
import hbsJson from '../admin/imgs/hbs.json';

export default {
  data() {
    return {
      zsyNum: '',
      syNum: '',
      ktNum: '',
      activeService: '信用租赁',
      nowTime: '',
      mid2Chart: null,
      resizeObserver: null,
      timerInterval: null
    };
  },
  methods: {
    updateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      const second = String(now.getSeconds()).padStart(2, '0');

      this.nowTime = `${year}年${month}月${day}日 ${hour}:${minute}:${second}\u00A0\u00A0\u00A0\u00A0`;
    },
    restLeft1(e) {
      const chartDom = document.getElementById('left1');
      const myChart = echarts.init(chartDom);
      const xAxisData = e.map(item => item.groups);
      const barData = e.map(item => item.syNum);
      const lineData = e.map(item => item.ktNum);
      const maxValue = Math.max(...barData, ...lineData);
      let interval = Math.ceil(maxValue / 5 / 50) * 50;

      if (interval < 50) {
        interval = Math.ceil(maxValue / 5 / 10) * 10;
      }
      if (interval < 10) {
        interval = Math.ceil(maxValue / 5);
      }

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
        },
        grid: {
          top: '10%',
          right: '9%',
          bottom: '5%',
          left: '8%',
          containLabel: true
        },
        xAxis: [{
          type: "category",
          data: xAxisData,
          axisPointer: {
            type: "shadow",
          },
          axisLabel: {
            color: '#fff'
          }
        }],
        yAxis: [{
            type: "value",
            min: 0,
            max: Math.ceil(maxValue * 1.2 / interval) * interval,
            interval: interval,
            axisLabel: {
              formatter: "{value}",
              color: '#fff'
            },
          },
          {
            type: "value",
            min: 0,
            max: Math.ceil(maxValue * 1.2 / interval) * interval,
            interval: interval,
            axisLabel: {
              formatter: "{value}",
              color: '#fff'
            },
          },
        ],
        series: [{
            name: "使用人数",
            type: "bar",
            itemStyle: {
              color: "#5087ec",
            },
            data: barData,
            yAxisIndex: 0,
          },
          {
            name: "开通人数",
            type: "line",
            yAxisIndex: 1,
            symbol: "circle",
            symbolSize: 4,
            itemStyle: {
              color: "#abd8dd",
            },
            data: lineData
          },
        ],
      };

      myChart.setOption(option);
    },
    restLeft2(e) {
      const chartDom = document.getElementById('left2');
      const myChart = echarts.init(chartDom);
      const xAxisData = e.map(item => item.groups);
      const barData = e.map(item => item.num);

      const option = {
        grid: {
          left: '9%',
          right: '10%',
          bottom: '2%',
          top: '10%',
          containLabel: false,
        },
        xAxis: {
          show: false,
        },
        yAxis: [{
          type: "category",
          data: xAxisData,
          axisTick: "none",
          axisLine: "none",
          axisLabel: {
            show: true,
            color: '#D0DEEE',
            align: 'top',
            verticalAlign: 'bottom',
            padding: [10, 0, 10, 10],
            fontSize: 20
          },
        }, {
          axisTick: "none",
          axisLine: "none",
          show: true,
          axisLabel: {
            fontSize: 20,
            position: 'insideRight',
            color: '#D0DEEE',
            align: 'top',
            verticalAlign: 'bottom',
            padding: [0, 0, 10, -50],
          },
          data: barData,
        }],
        series: [{
          name: 'value',
          type: 'bar',
          zlevel: 1,
          showBackground: true,
          backgroundStyle: {
            opacity: 0.098,
            color: '#FFFFFF',
            borderRadius: 20
          },
          itemStyle: {
            color: '#36A5FF',
            borderRadius: 20
          },
          barWidth: '20%',
          data: barData,
        }],
      };
      myChart.setOption(option);
    },
    restLeft3(e) {
      const chartDom = document.getElementById('left3');
      const myChart = echarts.init(chartDom);
      const xAxisData = e.map(item => item.groups);
      const seriesData = e.map(item => ({
        name: item.groups,
        value: item.num
      }));

      const option = {
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            z: 0
          },
          formatter: function(params) {
            return params[0].name + ': ' + params[0].value;
          },
          showContent: true
        },
        dataZoom: {
          show: true,
          type: 'slider',
          realtime: true,
          height: 10,
          start: 0,
          end: 80,
          textStyle: false,
        },
        xAxis: [{
          type: 'category',
          axisTick: {
            show: false,
            alignWithLabel: true
          },
          axisLabel: {
            color: '#fff',
            interval: 0
          },
          axisLine: {
            lineStyle: {
              color: '#2b386a',
              fontSize: 16
            }
          },
          data: xAxisData
        }],
        yAxis: [{
          type: 'value',
          splitNumber: 5,
          interval: 200,
          boundaryGap: ['0%', '10%'],
          splitLine: {
            show: false
          },
          axisLabel: {
            color: '#fff',
            fontSize: 16
          },
          axisLine: {
            lineStyle: {
              color: '#2b386a'
            }
          }
        }],
        series: [{
          name: '区域数据',
          type: 'bar',
          barWidth: 26,
          emphasis: {
            label: {
              show: true,
              position: 'top',
              distance: 8,
              textStyle: {
                color: '#fff',
                fontSize: 18
              }
            }
          },
          itemStyle: {
            normal: {
              show: true,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: '#07fb96'
                },
                {
                  offset: 1,
                  color: '#3149fc'
                }
              ])
            }
          },
          data: seriesData
        }]
      };
      myChart.setOption(option);
    },
    restMid1(e) {
      this.zsyNum = e.zsyNum;
      this.syNum = e.syNum;
      this.ktNum = e.ktNum;
    },
    restMid2(e) {
      const chartDom = document.getElementById('mid2');

      if (this.mid2Chart) {
        this.mid2Chart.dispose();
      }

      this.mid2Chart = echarts.init(chartDom);
      echarts.registerMap('hubei', hbsJson);

      const data = e.map(item => ({
        name: item.groups,
        value: item.num
      }));

      const maxValue = Math.max(...data.map(item => item.value));

      const option = {
        tooltip: {
          formatter: '{b}: {c}'
        },
        visualMap: {
          min: 0,
          max: maxValue,
          show: false,
          inRange: {
            color: ['#ffeeee', '#ffcccc', '#ff9999', '#ff6666', '#ff3333', '#ff0000']
          }
        },
        series: [{
          name: '地图数据',
          type: 'map',
          zoom: 1.1,
          roam: true,
          mapType: 'hubei',
          itemStyle: {
            normal: {
              borderColor: 'brown',
              areaColor: '#091e5d',
              borderWidth: 1,
              borderColor: '#ffcccc'
            },
            emphasis: {
              areaColor: '#ffcccc',
              label: {
                show: true,
                textStyle: {
                  color: 'darkslategray',
                },
              }
            }
          },
          data: data,
          label: {
            normal: {
              show: true,
              textStyle: {
                fontSize: 10,
                color: '#fff'
              }
            },
            emphasis: {
              textStyle: {
                color: '#fff'
              }
            }
          }
        }]
      };

      this.mid2Chart.setOption(option);
      this.resizeObserver = new ResizeObserver(() => {
        this.mid2Chart.resize();
      });
      this.resizeObserver.observe(chartDom);
    },
    restRight11(e) {
      const chartDom = document.getElementById('right1-1');
      const myChart = echarts.init(chartDom);
      var data = e.map(item => ({
        name: item.groups,
        value: item.num
      }));
      var colorScheme1 = ['#3daff6', '#4dc794', '#f76e6d', '#ffb980', '#8c9eff'];
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c} ({d}%)"
        },
        color: colorScheme1,
        series: [{
          name: "地区数据",
          type: "pie",
          radius: ["60%", "90%"],
          avoidLabelOverlap: false,
          roseType: 'radius',
          label: {
            show: true,
            position: "center",
            fontSize: 16,
            fontWeight: "bold",
            formatter: function() {
              return `{total|信用分占比}`;
            },
            rich: {
              total: {
                fontSize: 22,
                fontWeight: "bold",
                color: "#fff",
              },
            },
          },
          labelLine: {
            show: false
          },
          data: data,
        }],
      };
      myChart.setOption(option);
    },
    restRight12(e) {
      const chartDom = document.getElementById('right1-2');
      const myChart = echarts.init(chartDom);
      var data = e.map(item => ({
        name: item.groups,
        value: item.num
      }));
      var colorScheme1 = ['#ff7f50', '#87cefa', '#da70d6', '#32cd32', '#6495ed'];
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c} ({d}%)"
        },
        color: colorScheme1,
        series: [{
          name: "地区数据",
          type: "pie",
          radius: ["60%", "90%"],
          avoidLabelOverlap: false,
          roseType: 'radius',
          label: {
            show: true,
            position: "center",
            fontSize: 16,
            fontWeight: "bold",
            formatter: function() {
              return `{total|年龄分布}`;
            },
            rich: {
              total: {
                fontSize: 22,
                fontWeight: "bold",
                color: "#fff",
              },
            },
          },
          labelLine: {
            show: false
          },
          data: data,
        }],
      };
      myChart.setOption(option);
    },
    restRight13(e) {
      const chartDom = document.getElementById('right1-3');
      const myChart = echarts.init(chartDom);
      var data = e.map(item => ({
        name: item.groups,
        value: item.num
      }));
      var colorScheme1 = ['#dda0dd', '#90ee90', '#a0522d', '#d2691e', '#ff69b4'];
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c} ({d}%)"
        },
        color: colorScheme1,
        series: [{
          name: "地区数据",
          type: "pie",
          radius: ["60%", "90%"],
          avoidLabelOverlap: false,
          roseType: 'radius',
          label: {
            show: true,
            position: "center",
            fontSize: 16,
            fontWeight: "bold",
            formatter: function() {
              return `{total|性别分布}`;
            },
            rich: {
              total: {
                fontSize: 22,
                fontWeight: "bold",
                color: "#fff",
              },
            },
          },
          labelLine: {
            show: false
          },
          data: data,
        }],
      };
      myChart.setOption(option);
    },
    restRight14(e) {
      const chartDom = document.getElementById('right1-4');
      const myChart = echarts.init(chartDom);
      var data = e.map(item => ({
        name: item.groups,
        value: item.num
      }));
      var colorScheme1 = ['#e0ffff', '#bc8f8f', '#7fffd4', '#ffdab9', '#cd5c5c'];
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c} ({d}%)"
        },
        color: colorScheme1,
        series: [{
          name: "地区数据",
          type: "pie",
          radius: ["60%", "90%"],
          avoidLabelOverlap: false,
          roseType: 'radius',
          label: {
            show: true,
            position: "center",
            fontSize: 16,
            fontWeight: "bold",
            formatter: function() {
              return `{total|工作类型分布}`;
            },
            rich: {
              total: {
                fontSize: 22,
                fontWeight: "bold",
                color: "#fff",
              },
            },
          },
          labelLine: {
            show: false
          },
          data: data,
        }],
      };
      myChart.setOption(option);
    },
    restRight2(e) {
      const chartDom = document.getElementById('right2');
      const myChart = echarts.init(chartDom);

      const data = e.map((item, index) => ({
        name: item.groups,
        value: item.num,
        color: '#' + Math.floor(Math.random() * 16777215).toString(16)
      }));

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '25%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name),
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          },
          axisTick: {
            alignWithLabel: true,
            lineStyle: {
              color: '#fff'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.2)'
            }
          }
        },
        series: [{
          type: 'bar',
          barWidth: '60%',
          data: data.map(item => ({
            value: item.value,
            itemStyle: {
              color: item.color
            }
          })),
          label: {
            show: true,
            position: 'top',
            color: '#fff',
            formatter: '{c}'
          }
        }],
      };
      myChart.setOption(option);
    },
    getLeft1(serviceType) {
      this.activeService = serviceType;
      try {
        this.getReportData(`/rpt/left1?serverType=${serviceType}`, this.restLeft1);
      } catch (error) {
        console.error("Error fetching left2 data:", error);
      }
    },
    getReportData(url, handler) {
      request({
          url: url,
          method: 'get',
        })
        .then(response => {
          handler(response);
        })
        .catch(error => {
          console.error("Request failed:", error);
        });
    },
    initCharts() {
      this.getReportData('/rpt/left1?serverType=信用租赁', this.restLeft1);
      this.getReportData('/rpt/left2', this.restLeft2);
      this.getReportData('/rpt/left3', this.restLeft3);
      this.getReportData('/rpt/mid1', this.restMid1);
      this.getReportData('/rpt/mid2', this.restMid2);
      this.getReportData('/rpt/right11', this.restRight11);
      this.getReportData('/rpt/right12', this.restRight12);
      this.getReportData('/rpt/right13', this.restRight13);
      this.getReportData('/rpt/right14', this.restRight14);
      this.getReportData('/rpt/right2', this.restRight2);
  }
},
mounted() {
  this.updateTime();
  this.timerInterval = setInterval(this.updateTime, 1000);
  this.initCharts();
},
beforeDestroy() {
  // 组件销毁时，销毁图表实例和取消监听
  if (this.mid2Chart) {
    this.mid2Chart.dispose();
  }
  if (this.resizeObserver) {
    this.resizeObserver.disconnect();
  }
  // 清除定时器
  clearInterval(this.timerInterval);
}
};
</script>

<style scoped>
 @import '../admin/css/style.css';
</style>